from rest_framework import serializers
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from goods.models import SKU
from .models import User,Address
from celery_tasks.email.tasks import send_verify_email
#

class CreateUserSerializer(serializers.ModelSerializer):
    """注册序列化器"""

    password2 = serializers.CharField(label='密码2', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段
    """
    序列化器中需要的所有字段: 'id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
    模型中已有字段: id', 'username', 'mobile', 'password'
    需要进行序列化的字段: 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
    需要进行反序列化的字段:  'id', 'username', 'mobile'
    """

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow','token']
        extra_kwargs = {  # 对序列化器中的字段进行额外配置
                'username': {
                    'min_length': 5,
                    'max_length': 20,
                    'error_messages': {  # 自定义反序列化校验错误信息
                        'min_length': '仅允许5-20个字符的用户名',
                        'max_length': '仅允许5-20个字符的用户名',
                    }
                },
                'password': {
                    'write_only': True,  # 只做反序列化
                    'min_length': 8,
                    'max_length': 20,
                    'error_messages': {
                        'min_length': '仅允许8-20个字符的密码',
                        'max_length': '仅允许8-20个字符的密码',
                    }
                }
            }

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号格式有误')
        return value
    # def validate_allow(self, value):
    #     if value != True:
    #         raise serializers.ValidationError('请勾选同意协议')
    #     return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请勾选同意协议')
        return value

    def validate(self, attrs):
        if attrs.get('password') != attrs.get('password2'):
            raise serializers.ValidationError('两次密码不一致')
        # 校验验证码
        mobile =attrs.get('mobile')
        # 创建redis连接
        redis_conn =get_redis_connection('verify_codes')
        real_sms_code =redis_conn.get('sms_%s' % mobile)
        # 向redis存储数据时,都是以字符串的格式存储进行,将来获取出来后,都会变成'bytes'类型: str: bytes hash: {b'key':b''} list:[b'',] set:[b'']
        if not real_sms_code:
            raise serializers.ValidationError('验证码过期')
        if real_sms_code.decode() != attrs.get('sms_code'):
            raise serializers.ValidationError('验证码有误')
        return attrs
    def create(self,validated_date):
        """重写序列化器的保存方法把多余数据移除"""
        del validated_date['password2']
        del validated_date['sms_code']
        del validated_date['allow']

        password = validated_date.pop('password') # 把字典中的password移除

        user =User(**validated_date)
        user.set_password(password) # 对密码进行加密后再赋值给user模型对象的password属性
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER # 加载生成载荷函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER# 加载生成token的函数
        payload = jwt_payload_handler(user) # 通过传入user对象生成jwt 载荷部分
        token = jwt_encode_handler(payload) # 传入payload 生成token
        # 给user 模型对象多增加一个token属性,再给序列化器多增加token字段只做序列化
        user.token =token
        return user



class UserDetailSerializer(serializers.ModelSerializer):
    """用户信息展示序列化器"""
    class Meta:
        model = User
        fields = ['id','username','mobile','email','email_active']


class EmailSerializer(serializers.ModelSerializer):
    """设置邮箱"""
    class Meta:
        model = User
        fields =['id','email']
    # 因为email字段在模型中定义时,设置的可以为空,那么ModelSerializer在自动生成字段时,
    # 如果模型中设置字段可以为空,或有默认值,那么它required默认就会生成为False
    extra_kwargs={
        'email':{'required':True}
    }
    def update(self,instance,validated_data):
        instance.email = validated_data.get('email')
        instance.save()
        # 这里发邮件
        # 生成验证链接
        verify_url = instance.generate_email_verify_url()
        # 发送验证邮件
        send_verify_email.delay(instance.email, verify_url)
        return instance




class AddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

class AddressTitleSerializer(serializers.ModelSerializer):
        """
        地址标题
        """

        class Meta:
            model = Address
            fields = ('title',)




class UserBrowseHistorySerializer(serializers.Serializer):
    """
       添加用户浏览历史序列化器
       """
    sku_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    def validate_sku_id(self, value):
        """
        检验sku_id是否存在
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """
        保存
        """
        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']

        redis_conn = get_redis_connection("history")
        pl = redis_conn.pipeline()

        # 移除已经存在的本商品浏览记录
        pl.lrem("history_%s" % user_id, 0, sku_id)
        # 添加新的浏览记录
        pl.lpush("history_%s" % user_id, sku_id)
        # 只保存最多5条记录
        pl.ltrim("history_%s" % user_id, 0, 4)

        pl.execute()

        return validated_data